package com.admin.common.util;

import java.util.HashMap;
import java.util.Map;

public class ThreadLocalVariableHolder {

    private static ThreadLocal<Map<String, Object>> thread_local_variables = new ThreadLocal<>();

    /**
     * 保存一个线程变量
     *
     * @param key
     * @param value
     * @author qiuxs
     */
    public static void setVariable(String key, Object value) {
        getThreadMap().put(key, value);
    }

    /**
     * 获取线程变量
     *
     * @param key
     * @return
     * @author qiuxs
     */
    @SuppressWarnings("unchecked")
    public static <T> T getVariable(String key) {
        return (T) getThreadMap().get(key);
    }
    
    /**
     * 删除当前线程指定变量
     *
     * @author qiuxs
     */
    public static void remove(String key) {
        Map<String, Object> threadLocalMap = thread_local_variables.get();
        if (threadLocalMap != null) {
            threadLocalMap.remove(key);
        }
    }

    /**
     * 清空当前线程变量
     *
     * @author qiuxs
     */
    public static void clear() {
        Map<String, Object> threadLocalMap = thread_local_variables.get();
        if (threadLocalMap != null) {
            threadLocalMap.clear();
            thread_local_variables.set(null);
        }
    }

    /**
     * 获取当前线程变量集合
     *
     * @return
     * @author qiuxs
     */
    private static Map<String, Object> getThreadMap() {
        Map<String, Object> threadLocalMap = thread_local_variables.get();
        if (threadLocalMap == null) {
            threadLocalMap = new HashMap<>();
            thread_local_variables.set(threadLocalMap);
        }
        return threadLocalMap;
    }
}
